package com.ruoyi.foodworks.service;

import com.ruoyi.foodworks.domain.ReplyLike;
import com.ruoyi.foodworks.domain.ReplyLikeRequest;
import com.ruoyi.foodworks.mapper.ReplyLikeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 回复点赞Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-01-01
 */
@Service
public class ReplyLikeService {
    
    @Autowired
    private ReplyLikeMapper replyLikeMapper;
    
    /**
     * 回复点赞/取消点赞
     */
    @Transactional
    public Map<String, Object> likeReply(ReplyLikeRequest request) {
        Map<String, Object> result = new HashMap<>();
        
        // 检查是否已经点赞
        ReplyLike existingLike = replyLikeMapper.selectByReplyIdAndUserId(request.getReplyId(), request.getUserId());
        
        if (existingLike != null) {
            // 已点赞，取消点赞
            replyLikeMapper.deleteReplyLikeById(existingLike.getId());
            result.put("success", true);
            result.put("action", "unlike");
            result.put("message", "取消点赞成功");
        } else {
            // 未点赞，添加点赞
            ReplyLike like = new ReplyLike();
            like.setReplyId(request.getReplyId());
            like.setUserId(request.getUserId());
            replyLikeMapper.insertReplyLike(like);
            result.put("success", true);
            result.put("action", "like");
            result.put("message", "点赞成功");
        }
        
        // 获取最新点赞数
        Integer likeCount = replyLikeMapper.selectLikeCountByReplyId(request.getReplyId());
        result.put("likeCount", likeCount);
        
        return result;
    }
    
    /**
     * 获取回复点赞状态
     */
    public Map<Long, Boolean> getReplyLikeStatus(List<Long> replyIds, Long userId) {
        Map<Long, Boolean> likeStatusMap = new HashMap<>();
        
        if (replyIds == null || replyIds.isEmpty() || userId == null) {
            return likeStatusMap;
        }
        
        List<ReplyLike> likes = replyLikeMapper.selectByReplyIdsAndUserId(replyIds, userId);
        
        for (ReplyLike like : likes) {
            likeStatusMap.put(like.getReplyId(), true);
        }
        
        return likeStatusMap;
    }
    
    /**
     * 获取回复点赞数
     */
    public Map<Long, Integer> getReplyLikeCounts(List<Long> replyIds) {
        Map<Long, Integer> likeCountMap = new HashMap<>();
        
        if (replyIds == null || replyIds.isEmpty()) {
            return likeCountMap;
        }
        
        for (Long replyId : replyIds) {
            Integer likeCount = replyLikeMapper.selectLikeCountByReplyId(replyId);
            likeCountMap.put(replyId, likeCount);
        }
        
        return likeCountMap;
    }
}
